package org.zffc.boot.starter.service;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.zffc.boot.starter.dto.MqttMessageDTO;

@Service
public class MqttService {
    private final Logger logger = LoggerFactory.getLogger(MqttService.class);
    
    @Autowired
    private MqttClient mqttClient;

    // 发布消息
    public void publish(MqttMessageDTO dto) throws MqttException {
        MqttMessage message = new MqttMessage(dto.getPayload().getBytes());
        message.setQos(1);
        message.setRetained(false);
        mqttClient.publish(dto.getTopic(), message);
    }
    
    // 订阅主题
    public void subscribe(String topic) throws MqttException {
        mqttClient.subscribe(topic, (t, msg) -> {
            String payload = new String(msg.getPayload());
            logger.info("Received message: " + payload + " from topic: " + t);
        });
    }


    /**
     * 取消订阅
     * @param topics
     * @throws MqttException
     */
    public void unsubscribe(String[] topics) throws MqttException {
        if (mqttClient != null && mqttClient.isConnected()) {
            mqttClient.unsubscribe(topics);
            logger.info("Unsubscribed from topics: " + String.join(", ", topics));
        } else {
            logger.info("Cannot unsubscribe - MQTT client is not connected");
        }
    }
}